/**
 * Pinia状态管理 - 应用全局状态管理
 * 管理模板、需求、聊天会话等状态
 */
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Template, RequirementData, RequirementResponse } from '../api'
import { templateApi, requirementApi, chatApi } from '../api'

// 应用主store
export const useAppStore = defineStore('app', () => {
  // 状态
  const loading = ref(false)
  const error = ref<string | null>(null)
  
  // 模板相关状态
  const templates = ref<Template[]>([])
  const selectedTemplate = ref<Template | null>(null)
  
  // 需求相关状态
  const currentRequirement = ref<RequirementResponse | null>(null)
  const requirementData = ref<RequirementData | null>(null)
  
  // 聊天相关状态
  const currentSessionId = ref<string | null>(null)
  const chatMessages = ref<Array<{ role: 'user' | 'assistant', content: string, timestamp: number }>>([])
  const isGenerating = ref(false)
  
  // 计算属性
  const hasCurrentRequirement = computed(() => !!currentRequirement.value)
  const hasActiveSession = computed(() => !!currentSessionId.value)
  
  // 方法
  const setLoading = (value: boolean) => {
    loading.value = value
  }
  
  const setError = (message: string | null) => {
    error.value = message
  }
  
  const clearError = () => {
    error.value = null
  }
  
  // 模板相关方法
  const loadTemplates = async () => {
    try {
      setLoading(true)
      clearError()
      const data = await templateApi.getTemplates()
      templates.value = data
      // 默认选择第一个模板
      if (data.length > 0) {
        selectedTemplate.value = data[0]
      }
    } catch (err: any) {
      setError('加载模板失败: ' + (err.message || '未知错误'))
    } finally {
      setLoading(false)
    }
  }
  
  const selectTemplate = (template: Template) => {
    selectedTemplate.value = template
  }
  
  // 需求相关方法
  const submitRequirement = async (data: RequirementData) => {
    try {
      setLoading(true)
      clearError()
      const response = await requirementApi.submit(data)
      currentRequirement.value = response
      requirementData.value = data
      return response
    } catch (err: any) {
      setError('提交需求失败: ' + (err.message || '未知错误'))
      throw err
    } finally {
      setLoading(false)
    }
  }
  
  // 聊天相关方法
  const createChatSession = async (requirementId: string) => {
    try {
      setLoading(true)
      clearError()
      const response = await chatApi.createSession(requirementId)
      // 修复：正确访问响应数据中的session_id
      currentSessionId.value = response.data.session_id
      console.log('Store中设置sessionId:', response.data.session_id)
      return response.data
    } catch (err: any) {
      setError('创建会话失败: ' + (err.message || '未知错误'))
      throw err
    } finally {
      setLoading(false)
    }
  }
  
  const addChatMessage = (role: 'user' | 'assistant', content: string) => {
    chatMessages.value.push({
      role,
      content,
      timestamp: Date.now()
    })
  }
  
  const generateAIContent = async (message?: string) => {
    if (!currentRequirement.value || !currentSessionId.value) {
      throw new Error('缺少必要的会话信息')
    }
    
    try {
      isGenerating.value = true
      clearError()
      
      if (message) {
        addChatMessage('user', message)
      }
      
      const response = await chatApi.generate({
        requirement_id: currentRequirement.value.requirement_id,
        message,
        session_id: currentSessionId.value
      })
      
      addChatMessage('assistant', response.content)
      return response
    } catch (err: any) {
      setError('生成内容失败: ' + (err.message || '未知错误'))
      throw err
    } finally {
      isGenerating.value = false
    }
  }
  
  const clearChatMessages = () => {
    chatMessages.value = []
  }
  
  const resetApp = () => {
    currentRequirement.value = null
    requirementData.value = null
    currentSessionId.value = null
    chatMessages.value = []
    isGenerating.value = false
    clearError()
  }
  
  return {
    // 状态
    loading,
    error,
    templates,
    selectedTemplate,
    currentRequirement,
    requirementData,
    currentSessionId,
    chatMessages,
    isGenerating,
    
    // 计算属性
    hasCurrentRequirement,
    hasActiveSession,
    
    // 方法
    setLoading,
    setError,
    clearError,
    loadTemplates,
    selectTemplate,
    submitRequirement,
    createChatSession,
    addChatMessage,
    generateAIContent,
    clearChatMessages,
    resetApp
  }
})